import axios from "axios";
import { Toast } from 'react-vant'

const instance = axios.create({
    baseURL: import.meta.env.DEV ? import.meta.env.VITE_API + "/api/" : import.meta.env.VITE_API + "/api/",
});

// 请求拦截
instance.interceptors.request.use((config) => {
    const token = localStorage.getItem("token");
    if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
    }

    return config;
}, (err) => {
  Toast.info(err.response?.status);
    return Promise.reject(err);
});

// 响应拦截
instance.interceptors.response.use((res) => {
    const status = res.data?.status;
    console.log('res.data', res.config.method === "post" && status === 'ok', res.config.method === "post" && status !== 'ok')

    if (res.config.method === "post" && status === 'ok') {
      Toast.info('操作成功');
    }

    if (res.config.method === "post" && status !== 'ok') {
        Toast.info(status);
    }

    return res.data;
}, (err) => {
    // 报错提示
    const message = err.response?.data?.message;
    const reason = err.response?.data?.reason;
    const status = err.response?.status;
    const code = err.response?.data?.code;
    const noMsg = err.config.method === "post" && err.config?.data && JSON.parse(err.config.data)?.noMsg;

    // if (!noMsg) {
    //     if (message) {
    //         showFailToast(i18n.global.locale.value === "zh" ? message : reason);
    //     } else {
    //         showFailToast(err.response?.statusText);
    //     }
    // }

    console.log('status', status, err.response)

    if (code === 400) {
        Toast.info(message);
    }
    if (code === 500) {
        Toast.info(message);
    }
    // 自动退出登录
    if (status === 401 || message === "user not found") {
        Toast.info('登入已过期');
    } else {
        Toast.info(message);
    }

    return Promise.reject(err);
});

export default instance;